﻿using System;
using System.Configuration;
using System.IO;
using NH.Core.Model;
using NH.Data;
using NHibernate;
using NUnit.Framework;
using Tests.Infrastructure;

namespace Tests.Data
{
    [TestFixture]
    public abstract class SqliteDatabaseBase
    {
        private static string connection;

        private ITransaction currentTransaction;
        protected ISession currentSession;

        static SqliteDatabaseBase()
        {
            var connectionFormat = ConfigurationManager.ConnectionStrings[Constants.CONNECTION_FORMAT_KEY].ConnectionString;
            var dbFile = ConfigurationManager.AppSettings[Constants.DB_FILE_KEY];
            connection = string.Format(connectionFormat, dbFile);

            if (!File.Exists(dbFile))
            {
                DB.Migrate(Constants.DB_TYPE, connection);

                Console.WriteLine("DB file - doesn't exist, created new!!!");
            }
            else
            {
                Console.WriteLine("DB file - file exists!!!");
            }
        }

        [TestFixtureSetUp]
        public void FixtureSetup()
        {
            var config = new SqliteConfig(connection);
            DB.Init(config);

            Console.WriteLine("DB initialized, count of entities: [{0}]", DB.Factory.GetAllClassMetadata().Count);
        }

        [SetUp]
        public void Setup()
        {
            currentSession = DB.Factory.OpenSession();
            currentTransaction = currentSession.BeginTransaction();
        }

        [TearDown]
        public void Teardown()
        {
            currentTransaction.Rollback();
            currentSession.Clear();
            currentSession.Close();
        }

        protected int Count<T>() where T : BaseEntity
        {
            return currentSession.QueryOver<T>().RowCount();
        }

        protected void FlushAndClear()
        {
            currentSession.Flush();
            currentSession.Clear();
        }
    }
}